﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using ZQNB.Common;
using ZQNB.Web.Common.Controllers;
using ZQNB.Web.Common.Helpers;
using ZQNB.Web.Common.Models;

namespace ZQNB.Web.Controllers
{
    public class AccountController : NbBaseController
    {
        private readonly INbAuthenticationManager nbAuthenticationManager;

        public AccountController(INbAuthenticationManager nbAuthenticationManager)
        {
            this.nbAuthenticationManager = nbAuthenticationManager;
        }

        #region 登录登出页面、部分页

        /// <summary>
        /// 登录页
        /// </summary>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        ///// <summary>
        ///// ??
        ///// </summary>
        ///// <param name="returnUrl"></param>
        ///// <returns></returns>
        //[HttpGet]
        //[AllowAnonymous]
        //public ActionResult LoginInside(string returnUrl)
        //{
        //    ViewBag.ReturnUrl = returnUrl;
        //    return View();
        //}

        /// <summary>
        /// 异步弹出的登陆框
        /// </summary>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public ActionResult LoginDialog(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        public ActionResult Logout(string returnUrl)
        { 
            //应该由事件机制通知
            //string conn = System.Web.HttpContext.Current.User.Identity.Name;
            //SingleChat.SingleRemove(conn);
            SignOut(User.Identity.Name);
            return RedirectToLocal(returnUrl);
        }

        #endregion

        #region 以下是给ajax的异步操作接口

        [HttpPost]
        [AllowAnonymous]
        public ActionResult AjaxLogin(LoginAccount model)
        {
            var mr = new MessageResult();
            try
            {
                if (ModelState.IsValid)
                {
                    mr = Validate(model);
                    if (mr.Success)
                    {

                        SignIn(model.IdentityName, model.RememberMe);

                        mr.Success = true;
                        mr.Message = "登录成功";
                        return Json(mr, JsonRequestBehavior.AllowGet);
                    }
                }
            }
            catch (Exception ex)
            {
                mr.Success = false;
                mr.Message = ex.Message;
                return Json(mr, JsonRequestBehavior.AllowGet);
            }

            // If we got this far, something failed, redisplay form
            mr.Success = false;
            mr.Message = "登录失败";
            return Json(mr, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult AjaxLogout()
        {
            SignOut(User.Identity.Name);

            var mr = new MessageResult { Success = true, Message = "注销成功" };
            return Json(mr, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        [Authorize]
        public ActionResult AjaxChangePassword(ChangePassword model)
        {
            var mr = new MessageResult();
            try
            {
                if (ModelState.IsValid)
                {
                    mr = ChangePassword(model);
                    return Json(mr, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                mr.Success = false;
                mr.Message = ex.Message;
                return Json(mr, JsonRequestBehavior.AllowGet);
            }

            // If we got this far, something failed, redisplay form
            mr.Success = false;
            mr.Message = "修改失败";
            return Json(mr, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region helpers

        private MessageResult ChangePassword(ChangePassword model)
        {
            var mr = new MessageResult();
            if (model.NewPassword != model.ConfirmPassword)
            {
                mr.Message = "两次输入不一致";
                return mr;
            }

            mr = nbAuthenticationManager.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
            return mr;
        }

        //验证
        private MessageResult Validate(LoginAccount model)
        {
            MessageResult mr = nbAuthenticationManager.Validate(model.IdentityName, model.Password);
            return mr;
        }

        //登入
        private void SignIn(string identityName, bool isPersistent)
        {
            nbAuthenticationManager.Login(identityName, isPersistent);
        }

        //登出
        private void SignOut(string loginName)
        {
            if (!string.IsNullOrWhiteSpace(loginName))
            {
                nbAuthenticationManager.Logout(loginName);
            }
        }

        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (!string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            return Redirect("~/");
        }

        #endregion
    }
}